import { _decorator, Component } from 'cc';
import { WECHAT } from 'cc/env';
import { Loger } from '../loger/Loger';
const { ccclass, property } = _decorator;

@ccclass('InterstitialAd')
export class InterstitialAd extends Component {
    @property({ tooltip: '插屏广告ID' })
    adUnitId: string = '';

    @property({tooltip: '延迟展示（单位：秒）', min: 0})
    delay: number = 0;

    @property({tooltip: '加载后立即显示'})
    playOnLoad: boolean = true;

    ad: any;
    start() {
        //检测环境
        if (!WECHAT) {
            Loger.log('非微信环境，退出！')
            return;
        }

        if (!this.adUnitId) {
            Loger.log('末配置插屏广告ID')
            return;
        }

        this.ad = wx.createInterstitialAd({ adUnitId:this.adUnitId });   

        if (this.playOnLoad) {
            this.show();
        }
    }

    show() {
        if (this.delay) {
            this.scheduleOnce(() => {
                this.ad.show().catch((err) => {
                    Loger.error(err)
                });
            }, this.delay);
        } else {
            this.ad.show().catch((err) => {
                Loger.error(err)
            });
        }
    }

    onDestroy() {
        this.ad = null;
    }

}

